/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.hot.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.hot.domain.HotRecord;
import com.fzhucc.modules.hot.domain.dto.HotRecordQueryCriteria2;
import com.fzhucc.modules.hot.domain.dto.HotRecordScaleCriteria;
import com.fzhucc.utils.ValidationUtil;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.hot.repository.HotRecordRepository;
import com.fzhucc.modules.hot.domain.dto.HotRecordDto;
import com.fzhucc.modules.hot.domain.dto.HotRecordQueryCriteria;
import com.fzhucc.modules.hot.service.mapstruct.HotRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-29
 **/
@Service
@RequiredArgsConstructor
public class HotRecordService {

    private final HotRecordRepository hotRecordRepository;
    private final HotRecordMapper hotRecordMapper;

    public Map<String, Object> queryAll(HotRecordQueryCriteria criteria, Pageable pageable) {
        Page<HotRecord> page = hotRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(hotRecordMapper::toDto));
    }

    public void scaleData(HotRecordScaleCriteria dto) {
        String startstr = dto.getStart();
        String endstr = dto.getEnd();
        String orgArea = dto.getOrgArea();
        if (startstr == null) {
            throw new BadRequestException("请输入开始时间");
        }
        if (startstr.equals("")) {
            throw new BadRequestException("请输入开始时间");
        }
        if (endstr == null) {
            throw new BadRequestException("请输入结束时间");
        }
        if (endstr.equals("")) {
            throw new BadRequestException("请输入结束时间");
        }
        if (orgArea == null) {
            throw new BadRequestException("请输入地区组织");
        }
        if (orgArea.equals("")) {
            throw new BadRequestException("请输入地区组织");
        }
        if (!orgArea.equals("福州市")) {
            throw new BadRequestException("目前仅支持特定地区使用");
        }

        int needCount = dto.getNeedCount();//需要导入的数据总数
        int count=0;
        List<LocalDateTime> list = new ArrayList<LocalDateTime>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.parse(startstr, formatter);
        LocalDateTime end = LocalDateTime.parse(endstr, formatter);
        Duration duration = Duration.between(start, end);
        long secondsBetween = duration.getSeconds();
        for (int i = 0; i < secondsBetween; i++) {
            LocalDateTime currentTime = start.plusSeconds(i);
            count = count + 1;
            list.add(currentTime);
        }
        //如果需要的总数小于等于  遍历后的数据的数量 则使用需求数作为<依据
        if (needCount<=count){
            for (int i = 0; i < needCount; i++){
                LocalDateTime localDateTime = list.get(i);
                HotRecord hotRecord = new HotRecord();
                hotRecord.setOrgArea("福州市");
                hotRecord.setInTime(Timestamp.valueOf(localDateTime));
                hotRecordRepository.save(hotRecord);
            }
        }else{
            int multiple = findMultiple(count, needCount);
            //相差的倍率
            for (int j = 0; j < multiple; j++) {
                for (int i = 0; i < count; i++) {
                    LocalDateTime localDateTime = list.get(i);
                    HotRecord hotRecord = new HotRecord();
                    hotRecord.setOrgArea("福州市");
                    hotRecord.setInTime(Timestamp.valueOf(localDateTime));
                    hotRecordRepository.save(hotRecord);
                }
            }
            int useCount = multiple * count;
            int unCount = needCount - useCount;
            for (int i = 0; i < unCount; i++) {
                LocalDateTime localDateTime = list.get(i);
                HotRecord hotRecord = new HotRecord();
                hotRecord.setOrgArea("福州市");
                hotRecord.setInTime(Timestamp.valueOf(localDateTime));
                hotRecordRepository.save(hotRecord);
            }
        }
    }

    //求相差多少倍
    public static int findMultiple(int num1, int num2) {
        int max = Math.max(num1, num2);
        int min = Math.min(num1, num2);
        return max / min;
    }

    public List<HotRecordDto> queryAll(HotRecordQueryCriteria criteria) {
        return hotRecordMapper.toDto(hotRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public List<HotRecordDto> queryAll2(HotRecordQueryCriteria2 criteria) {
        String start = criteria.getStart();
        String end = criteria.getEnd();
        String orgArea = criteria.getOrgArea();
        if (orgArea == null) {
            //查所有
            if (start == null && end == null) {
                //查所有
                List<HotRecord> all = hotRecordRepository.findAll();
                return hotRecordMapper.toDto(all);
            } else {
                if (start == null && end != null) {
                    throw new BadRequestException("请输入开始时间");
                } else if (start != null && end == null) {
                    throw new BadRequestException("请输入结束时间");
                } else {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        String s = start + " 00:00:00";
                        String e = end + " 23:59:59";
                        Date startDate = formatter.parse(s);
                        Date endDate = formatter.parse(e);
                        List<HotRecord> all = hotRecordRepository.findNormalByInTime(startDate, endDate);
                        return hotRecordMapper.toDto(all);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            if (start == null && end == null) {
                List<HotRecord> all = hotRecordRepository.findNormalByLikeArea("%" + orgArea + "%");
                return hotRecordMapper.toDto(all);
            } else {
                if (start == null && end != null) {
                    throw new BadRequestException("请输入开始时间");
                } else if (start != null && end == null) {
                    throw new BadRequestException("请输入结束时间");
                } else {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        String s = start + " 00:00:00";
                        String e = end + " 23:59:59";
                        Date startDate = formatter.parse(s);
                        Date endDate = formatter.parse(e);
                        List<HotRecord> all = hotRecordRepository.findNormalByInTimeWithArea(startDate, endDate, "%" + orgArea + "%");
                        return hotRecordMapper.toDto(all);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
        //return hotRecordMapper.toDto(hotRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public HotRecordDto findById(Integer id) {
        HotRecord hotRecord = hotRecordRepository.findById(id).orElseGet(HotRecord::new);
        ValidationUtil.isNull(hotRecord.getId(), "HotRecord", "id", id);
        return hotRecordMapper.toDto(hotRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    public HotRecordDto create(HotRecord resources) {
        return hotRecordMapper.toDto(hotRecordRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(HotRecord resources) {
        HotRecord hotRecord = hotRecordRepository.findById(resources.getId()).orElseGet(HotRecord::new);
        ValidationUtil.isNull(hotRecord.getId(), "HotRecord", "id", resources.getId());
        hotRecord.copy(resources);
        hotRecordRepository.save(hotRecord);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            hotRecordRepository.deleteById(id);
        }
    }

    public void download(List<HotRecordDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (HotRecordDto hotRecord : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("访问时间", hotRecord.getInTime());
            map.put("工会", hotRecord.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}